package com.cinema.model;

import java.time.LocalDateTime;
import java.util.UUID;
import java.time.format.DateTimeFormatter;

public class Ticket {
    private String ticketId;
    private Screening screening;
    private String seatNumber;
    private double price;
    private double discount;
    private LocalDateTime purchaseTime;
    private String purchaser;
    private TicketStatus status;

    public Ticket(Screening screening, String seatNumber, String purchaser) {
        this.ticketId = "T" + UUID.randomUUID().toString().substring(0, 8);
        this.screening = screening;
        this.seatNumber = seatNumber;
        this.price = screening.getPrice();
        this.discount = calculateDiscount();
        this.purchaseTime = LocalDateTime.now();
        this.purchaser = purchaser;
        this.status = TicketStatus.VALID;
    }

    private double calculateDiscount() {
        // 简单的折扣策略：早上场次9折
        int hour = purchaseTime.getHour();
        return hour < 12 ? 0.9 : 1.0;
    }

    public double getFinalPrice() {
        return price * discount;
    }

    public boolean canRefund() {
        return LocalDateTime.now().isBefore(screening.getStartTime().minusHours(1));
    }

    public double getRefundAmount() {
        if (!canRefund()) return 0;

        long hoursUntilScreening = java.time.Duration.between(
                LocalDateTime.now(), screening.getStartTime()).toHours();

        if (hoursUntilScreening > 24) {
            return getFinalPrice(); // 全额退款
        } else {
            return getFinalPrice() * 0.9; // 扣除10%
        }
    }

    // Getters and Setters
    public String getTicketId() { return ticketId; }
    public Screening getScreening() { return screening; }
    public String getSeatNumber() { return seatNumber; }
    public double getPrice() { return price; }
    public double getDiscount() { return discount; }
    public LocalDateTime getPurchaseTime() { return purchaseTime; }
    public String getPurchaser() { return purchaser; }
    public TicketStatus getStatus() { return status; }
    public void setStatus(TicketStatus status) { this.status = status; }

    @Override
    public String toString() {
        return String.format("票号: %s\n电影: %s\n场次: %s\n座位: %s\n价格: ¥%.2f\n时间: %s",
                ticketId, screening.getMovie().getTitle(),
                screening.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),
                seatNumber, getFinalPrice(), purchaseTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }
}

